from django.shortcuts import render
from django.views import View
from meiduo_mall import settings
from QQLoginTool.QQtool import OAuthQQ
from django.http import JsonResponse
from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from django.contrib.auth import login

import json
# Create your views here.
class QQLoginURLView(View):
    def get(self, request):
        qq = OAuthQQ(client_id=settings.BQCLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx'
                     )
        qq_login_url = qq.get_qq_url()
        print(qq_login_url)
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': qq_login_url})


class OAuthView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        qq = OAuthQQ(client_id=settings.BQCLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx'
                     )
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)
        try:
            qquser=OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            from utils.tools import encrypt
            return JsonResponse({'code':400,'access_token':encrypt(openid)})
        else:
            login(request,qquser.user.username)
            response=JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('username',qquser.user.username)
            return response

class OAuthQQView(View):
    def get(self,request):...
    def post(self,request):
        data=json.loads(request.body.decode())
        mobile=data.get('mobile')
        password = data.get('password')
        sms_code = data.get('sms_code')
        access_token = data.get('access_token')
        from utils.tools import decrypt
        openid=decrypt(access_token)
        try:
            user=User.objects.get(mobile=mobile)
        except:
            user=User.objects.create_user(username=mobile,mobile=mobile,password=password)
        else:
            if not user.check_password(password):
                return JsonResponse({'code':400,'errmsg':'账号或密码错误'})
        OAuthQQUser.objects.create(user=user,openid=openid)
        login(request,user)
        response=JsonResponse({'code':0,'errmsg':'ok'})
        response.set_cookie('username',user.username)
        return response


